package mytest;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/updateContact")
public class UpdateContactServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("contactId");
        String newName = request.getParameter("name");
        String newAddress = request.getParameter("address");
        String newPhone = request.getParameter("phone");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact", "root", "root123");
            PreparedStatement ps = conn.prepareStatement("UPDATE contacts SET name = ?, address = ?, phone = ? WHERE id = ?");
            ps.setString(1, newName);
            ps.setString(2, newAddress);
            ps.setString(3, newPhone);
            ps.setInt(4, Integer.parseInt(id));
            ps.executeUpdate();

            // 重定向到联系人列表页面
            response.sendRedirect("/contact");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

